<?php
namespace app\index\controller;
use think\Controller;
use think\Db;

/*
    │＼＿＿╭╭╭╭╭＿＿／│
　　│　　　　　　　　　│
　　│　　　　　　　　　│
　　│　－　　　　　　－│
　　│≡　　　ｏ　　　  ≡│
　　│　　　　　　　　  │
　　╰──┬Ｏ◤▽◥Ｏ┬──╯
　　  ｜　　ｏ　　｜
    cat never have bug
*/
class Auto extends Controller
{
    /*   
        功能: 分解订单;
        参数: 无
        返回值: 无
    */
    public function reduceOrder(){
        $OrderList = $this->getOrderList();
        $needCutList = array();
        for($i =0;$i <count($OrderList);$i++){
            if($OrderList[$i]["volume"] >50){
                array_push($needCutList,$OrderList[$i]);
            }
        }
        foreach ($needCutList as $needCut) {
            $needReduce = (int)($needCut["volume"]/50);
            $id = $needCut["id"];
            array_splice($needCut,0,1);
            for ($i = 0; $i <= $needReduce;$i ++) {
                if($i === 0){
                    $needCut["volume"]= $needCut["volume"]-50*$needReduce;
                }else{
                    $needCut["volume"]= 50;
                }
                Db::table("all_data")->insert($needCut);
            }
            Db::table('all_data')->delete($id);
            
        }
    }
    /*
        功能: 获得未分配订单列表;
        参数: 无
        返回值: 未分配订单列表
    */
    public function getOrderList(){
        $OrderList = Db::table('all_data')->where('state',3)->select();
        return $OrderList;
    }
    /*
        功能: 去掉已未分配订单中的已分配列表;
        参数: {
                spliceId: 已分配订单的序号
                OrderList: 未分配订单列表
            }
        返回值: 无
    */
    public function toSplice($spliceId,&$OrderList){
        for($i =0;$i < count($spliceId); $i ++) {
            array_splice($OrderList,$spliceId[$i],1);
            $spliceId = array_map(function($a)
            {
                return $a-1;
            },$spliceId);
        }
    }
    /*
        功能: 根据地点和体积配单;
        参数: {
                OrderList: 已分配订单的序号
                processed_data: 分配后的id数组
            }
        返回值: bool 判断是否继续循环
    */
    public function matching(&$OrderList,&$processed_data){
        if(count($OrderList)){
            $spliceId = array();
            $order = $OrderList[0];
            $processed_id = array();
            $processed_volume = $order["volume"];
            $id = array();
            array_push($id,$OrderList[0]["id"]);
            array_push($processed_id,$OrderList[0]);
            array_splice($OrderList,0,1);
            for($i = 0; $i < count($OrderList); $i++){
                if($order["bourn"] === $OrderList[$i]["bourn"]){
                    $processed_volume += $OrderList[$i]["volume"]; 
                    if($processed_volume < 45){
                        array_push($processed_id,$OrderList[$i]);
                        array_push($id,$OrderList[$i]["id"]);
                        array_push($spliceId,$i);
                    }else if($processed_volume >45 && $processed_volume<55){
                        array_push($processed_id,$OrderList[$i]);
                        array_push($id,$OrderList[$i]["id"]);
                        array_push($spliceId,$i);
                        $data["processed_id"] = $processed_id;
                        $data["processed_volume"] = $processed_volume;
                        $data["enough"] = true;
                        $data["id"] = $id;
                        array_push($processed_data,$data);
                        $this->toSplice($spliceId,$OrderList);
                        return false;
                    }else{
                        $processed_volume -= $OrderList[$i]["volume"]; 
                    }
                }
            }
            $data["processed_id"] = $processed_id;
            $data["processed_volume"] = $processed_volume;
            $data["enough"] = false;
            $data["id"] = $id;
            $this->seachMatchingBourn($order,$OrderList,$data);
            array_push($processed_data,$data);
            $this->toSplice($spliceId,$OrderList);
            return false;
        }else{
            return true;
        }
        
    }
    /*
        功能: 根据相关地点和体积配单;
        参数: {
                order: 当前分配订单
                OrderList: 已分配订单的序号
                data: 分配结果
            }
        返回值: bool 判断是否继续循环
    */
    public function seachMatchingBourn($order,&$OrderList,&$data){
        $oneBourn = $order["bourn"];
        $spliceId = array();
        for($i = 0; $i < count($OrderList); $i ++){
            $twoBourn = $OrderList[$i]["bourn"];
            $result = Db::table('alldata_2017_address_weight') 
                ->field('address02,SUM(weightnum)')
                ->where('address01',$oneBourn)
                ->where('address02',$twoBourn)
                ->group('address02')
                ->order('SUM( weightnum) DESC')
                ->find();
            if($result["SUM(weightnum)"]){
                $allVolume = $data["processed_volume"]+$OrderList[$i]["volume"];
                if($allVolume < 45){
                    array_push($data["processed_id"],$OrderList[$i]);
                    array_push($data["id"],$OrderList[$i]["id"]);
                    array_push($spliceId,$i);
                    $data["processed_volume"] = $allVolume;
                }else if($allVolume >45 && $allVolume<55){
                    array_push($data["processed_id"],$OrderList[$i]);
                    array_push($data["id"],$OrderList[$i]["id"]);
                    array_push($spliceId,$i);
                    $data["processed_volume"] = $allVolume;
                    $data["enough"] = true;
                    $this->toSplice($spliceId,$OrderList);
                    return false;
                }
            }
        }
        $this->toSplice($spliceId,$OrderList);
    }

    public function possibilityAnalysis($oneProcessed_data,&$processed_data){
        $customers = array();
        foreach ($oneProcessed_data as $od) {
            array_push($customers,$od["customer"]);
        }
        $customers = array_unique($customers);
        $date = array();
        array_push($date,date_format(
                    date_create(
                        $oneProcessed_data[0]["createdate"]
                    ),
                    "Y-m-d"
                )
            );
        array_push(
            $date,
            date_format(
                    date_sub(
                            date_create(
                                $oneProcessed_data[0]["createdate"]
                            )
                        ,
                        date_interval_create_from_date_string("1 days")
                    ),
                    "Y-m-d"
                )
        );
        array_push(
            $date,
            date_format(
                    date_sub(
                            date_create(
                                $oneProcessed_data[0]["createdate"]
                            )
                        ,
                        date_interval_create_from_date_string("2 days")
                    ),
                    "Y-m-d"
                )
        );
        $probabilitys = 0;
        foreach ($customers as $customer) {
            $result = Db::table('alldata_2017_address_weight') 
                ->field('user02')
                ->where('user01',$customer)
                ->group('user02')
                ->order('SUM( weightnum) DESC')
                ->limit(3)
                ->select();
            $density = 0;
            $threeDensity = 0;
            foreach ($result as $r) {
                $wantCustomer = $r["user02"];
                $densitys = Db::table("temp_table1")->where("客户名称",$wantCustomer)->find();
                foreach ($date as $key) {
                    $threeDensityOneCount = Db::query("SELECT COUNT(createdate) 
                        FROM all_data 
                        WHERE createdate = $key
                        AND customer = '$wantCustomer'
                    ");
                    $threeDensity += $threeDensityOneCount[0]['COUNT(createdate)'];
                }
                switch ((int)date('m')) {
                    case 1:
                        $density += $densitys["1月"];
                        break;
                    case 2:
                        $density += $densitys["2月"];
                        break;
                     case 3:
                        $density += $densitys["3月"];
                        break;
                     case 4:
                        $density += $densitys["4月"];
                        break;
                     case 5:
                        $density += $densitys["5月"];
                        break;
                     case 6:
                        $density += $densitys["6月"];
                        break;
                     case 7:
                        $density += $densitys["7月"];
                        break;
                     case 8:
                        $density += $densitys["8月"];
                        break;
                     case 9:
                        $density += $densitys["9月"];
                        break;
                     case 10:
                        $density += $densitys["10月"];
                        break;
                     case 11:
                        $density += $densitys["11月"];
                        break;
                     case 12:
                        $density += $densitys["12月"];
                        break;
                }
            }
            $probabilitys += ($density - $threeDensity/3);
        }
        $processed_data["probability"] = $probabilitys/count($oneProcessed_data);
    }
    /*
        功能: 自动分单入空;
        参数: 无
        返回值: 无
    */
    public function autoProduction(){
        $this->reduceOrder();
        $OrderList = $this->getOrderList();
        $processed_data = array();
        $havingList = false;
        while(!$havingList) {
            $havingList = $this->matching($OrderList,$processed_data);
        }
        for($i = 0; $i < count($processed_data); $i++){
            if(!$processed_data[$i]["enough"]){
                $this->possibilityAnalysis($processed_data[$i]["processed_id"],$processed_data[$i]);
            }
        }
        // 根据车进行分配
        // $week = date('w');
        // $week = 0;
        // $truckid = '';
        // for($i = 0; $i < count($processed_data); $i++){
        //     $volume = $processed_data[$i]["processed_volume"];
        //     switch ($week) {
        //         case 0:
        //             $truckid = Db::query("SELECT all_user.truckid 
        //             FROM truck_week,vehicle_load,all_user
        //             WHERE volume > '$volume'
        //             AND all_user.truckid = vehicle_load.licensePlate
        //             AND truck_week.truckid = vehicle_load.licensePlate
        //             AND all_user.truckid = truck_week.truckid
        //             AND all_user.state = 0
        //             AND all_user.singlestate = 1
        //             ORDER BY Sunday
        //             LIMIT 1");
        //             break;
        //         case 6:
        //             $truckid = Db::query("SELECT all_user.truckid 
        //             FROM truck_week,vehicle_load,all_user
        //             WHERE volume > '$volume'
        //             AND all_user.truckid = vehicle_load.licensePlate
        //             AND truck_week.truckid = vehicle_load.licensePlate
        //             AND all_user.truckid = truck_week.truckid
        //             AND all_user.state = 0
        //             AND all_user.singlestate = 1
        //             ORDER BY Saturday
        //             LIMIT 1");
        //             break;
        //         default:
        //             $truckid = Db::query("SELECT all_user.truckid 
        //             FROM truck_week,vehicle_load,all_user
        //             WHERE volume > '$volume'
        //             AND all_user.truckid = vehicle_load.licensePlate
        //             AND truck_week.truckid = vehicle_load.licensePlate
        //             AND all_user.truckid = truck_week.truckid
        //             AND all_user.state = 0
        //             AND all_user.singlestate = 1
        //             LIMIT 1");
        //             break;
        //     }
        //             if(count($truckid)){
        //                 $truckid = $truckid[0]["truckid"];
        //                 Db::query("UPDATE all_user
        //                     SET state = 1
        //                     WHERE truckid = '$truckid'
        //                 ");
        //             }else {
        //                 $truckid = 0;
        //             }
                    
        //     $processed_data[$i]["truckid"] = $truckid;
        // }
        $ut = new Utiltool($processed_data);
        return $ut->getpdata();
    }   
    
}